package org.jix.weblog.module.jwt.service;

import lombok.extern.slf4j.Slf4j;
import org.jix.weblog.module.common.domain.dos.UserDO;
import org.jix.weblog.module.common.domain.dos.UserRoleDO;
import org.jix.weblog.module.common.domain.mapper.UserMapper;
import org.jix.weblog.module.common.domain.mapper.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @Author Jix
 * @Date 2024/7/21 18:01
 * @注释 UserDetailService是由Spring security提供的接口，用于加载用户信息以及创建userDetails对象
 * 此处为自定义实现类
 */

@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 从数据库中查询
        UserDO userDO = userMapper.selectByUsername(username);
        // 判断用户是否存在
        if (Objects.isNull(userDO)) {
            throw new UsernameNotFoundException("该用户不存在"+username);
        }
        //用户角色
        List<UserRoleDO> userRoleDOS = userRoleMapper.selectByUsername(username);
        String[] roleArr = null;
        //转数组
        if (!CollectionUtils.isEmpty(userRoleDOS)) {
            List<String> roles = userRoleDOS.stream().map(p -> p.getRole()).collect(Collectors.toList());
            roleArr = roles.toArray(new String[roles.size()]);
        }
        // authorities 用于指定角色，这里写死为 ADMIN 管理员
        return User.withUsername(userDO.getUsername())
                .password(userDO.getPassword())
                .authorities(roleArr)
                .build();
    }
}
